package com.ericdm.callingandsmsstatistics;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import com.ericdm.listviewwithcheckbox.ListViewAdapterIncommingCall;
import com.ericdm.listviewwithcheckbox.ListViewAdapterOutgoincCall;
import com.ericdm.listviewwithcheckbox.ListViewAdapterReceviedSms;
import com.ericdm.listviewwithcheckbox.ListViewAdapterSendedSms;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.format.Time;
import android.view.ContextMenu;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;

public class MainActivity extends Activity {
	boolean leap = false;
	private TextView startTime = null;
	private TextView endTime = null;
	private Button setTimeButton = null;
	private Button setStartTimeButton = null;
	private Button setEndTimeButton = null;
	private Button callButton = null;
	private Button yesButton = null;
	private Button noButton = null;
	private Button selectAllButton = null;
	private Button deselectButton = null;
	private Button deleteSelectedButton = null;
	private Button inverseSelectedButton = null;
	private Button contactsButton = null;
	private TabHost tabHost = null;
	private ListView listViewAll = null;
	private ListView listViewOutgoingCalls = null;
	private ListView listViewIncommingCalls = null;
	private ListView listViewSendedSMS = null;
	private ListView listViewReceviedSMS = null;
	private MyHanlder myHandler;
	private static ProgressDialog dialog;
	private ListViewAdapterOutgoincCall mListViewAdapterOutgoincCall;
	private ListViewAdapterIncommingCall mListViewAdapterIncommingCall;
	private ListViewAdapterReceviedSms mListViewAdapterReceviedSms;
	private ListViewAdapterSendedSms mListViewAdapterSendedSms;
	private ArrayList<String> list;
	public static String queryTime_Start = "";
	public static String queryTime_End = "";
	
    private static final int SWIPE_MIN_DISTANCE = 120;  
    private static final int SWIPE_MAX_OFF_PATH = 250;  
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private static int maxTabIndex = 4;
    int currentView = 0;  
    private GestureDetector gestureDetector;  
    View.OnTouchListener gestureListener;  
    
	private static final String TAB1_SUMMARY = "总计";
	private static final String TAB2_OUTGOINGCALLS = "拨打电话";
	private static final String TAB3_INCOMMINGCALLS = "接听电话";
	private static final String TAB4_SENDEDSMS = "发送短信";
	private static final String TAB5_RECEIEDSMS = "接收短信";
	public static int outGoingCallEnd = 0;
	public static Boolean isOutGoingCall = false;
	@SuppressLint("SimpleDateFormat")
	DateFormat fmtDateAndTime = new SimpleDateFormat("yyyy-MM-dd");
	Calendar dateAndTime = Calendar.getInstance(Locale.CHINA);

	DatePickerDialog.OnDateSetListener setStartTime = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			// TODO Auto-generated method stub
			dateAndTime.set(Calendar.YEAR, year);
			dateAndTime.set(Calendar.MONTH, monthOfYear);
			dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			queryTime_Start = fmtDateAndTime.format(dateAndTime.getTime());
		}
	};

	DatePickerDialog.OnDateSetListener setEndTime = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			// TODO Auto-generated method stub
			dateAndTime.set(Calendar.YEAR, year);
			dateAndTime.set(Calendar.MONTH, monthOfYear);
			dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			queryTime_End = fmtDateAndTime.format(dateAndTime.getTime());
		}
	};

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_main);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
		startTime = (TextView) findViewById(R.id.startTime);
		endTime = (TextView) findViewById(R.id.endTime);
		setTimeButton = (Button) findViewById(R.id.setDateTime);
		selectAllButton = (Button) findViewById(R.id.selectAll);
		deselectButton = (Button) findViewById(R.id.deselectAllItem);
		contactsButton = (Button)findViewById(R.id.contacts_btn);
		deleteSelectedButton = (Button) findViewById(R.id.deleteItem);
		inverseSelectedButton = (Button) findViewById(R.id.inverseSelected);
		callButton = (Button) findViewById(R.id.call_btn);
		tabHost = (TabHost) this.findViewById(R.id.theTabHost);
		listViewAll = (ListView) findViewById(R.id.listViewAll);
		listViewOutgoingCalls = (ListView) findViewById(R.id.listViewOutgoingCalls);
		listViewIncommingCalls = (ListView) findViewById(R.id.listViewIncommingCalls);
		listViewSendedSMS = (ListView) findViewById(R.id.listViewSendedSMS);
		listViewReceviedSMS = (ListView) findViewById(R.id.listViewReceviedSMS);
		setTimeButton.setOnClickListener(changeTimeButonListener);
		
		selectAllButton.setVisibility(View.INVISIBLE);
		deselectButton.setVisibility(View.INVISIBLE);
		deleteSelectedButton.setVisibility(View.INVISIBLE);
		inverseSelectedButton.setVisibility(View.INVISIBLE);

		selectAllButton.setOnClickListener(selectAllButtonListener);
		deselectButton.setOnClickListener(deselectAllItemsListener);
		inverseSelectedButton.setOnClickListener(inverseSelectedListener);
		deleteSelectedButton.setOnClickListener(deleteButtonListener);
		contactsButton.setOnClickListener(contactsButtonListener);
		callButton.setOnClickListener(callButtonListener);

		DatabaseOperator databaseOperator = new DatabaseOperator();
		queryTime_Start = databaseOperator.QueryTimeStrat();
		queryTime_End = databaseOperator.QueryTimeEnd();
		if (queryTime_Start.equals("") || queryTime_End.equals("")) {
			Time currentTime = new Time();
			currentTime.setToNow();
			int year = currentTime.year;
			int endYear = year + 5;
			int month = currentTime.month + 1;
			leap = isLeapYear(year);
			queryTime_Start = year + "-" + modifyMonth(month) + "-01";
			startTime.setText(queryTime_Start);
			if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
				queryTime_End = endYear + "-" + modifyMonth(month) + "-31";
				endTime.setText(queryTime_End);
			} else {
				if (month == 2 && leap) {
					queryTime_End = endYear + "-" + modifyMonth(month) + "-28";
					endTime.setText(queryTime_End);
				} else {
					queryTime_End = endYear + "-" + modifyMonth(month) + "-30";
					endTime.setText(queryTime_End);
				}
			}
			databaseOperator.insertQueryTime(queryTime_Start, queryTime_End);
		} else {
			startTime.setText( queryTime_Start);
			endTime.setText(queryTime_End);
		}

		startTime.setTextColor(android.graphics.Color.YELLOW);
		endTime.setTextColor(android.graphics.Color.YELLOW);
		tabHost.setup();

		myHandler = new MyHanlder();
		QueryDataThread queryDataThread = new QueryDataThread();
		new Thread(queryDataThread).start();

		
		dialog = new ProgressDialog(MainActivity.this);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
/*
		dialog.setTitle("检索数据");
		dialog.setMessage("数据更新中，请稍后");
		dialog.setIcon(android.R.drawable.ic_dialog_map);
		dialog.show();
*/
		tabHost.addTab(tabHost.newTabSpec(TAB1_SUMMARY).setIndicator(TAB1_SUMMARY).setContent(R.id.listViewAll));
		tabHost.addTab(tabHost.newTabSpec(TAB2_OUTGOINGCALLS).setIndicator(TAB2_OUTGOINGCALLS).setContent(R.id.listViewOutgoingCalls));
		tabHost.addTab(tabHost.newTabSpec(TAB3_INCOMMINGCALLS).setIndicator(TAB3_INCOMMINGCALLS).setContent(R.id.listViewIncommingCalls));
		tabHost.addTab(tabHost.newTabSpec(TAB4_SENDEDSMS).setIndicator(TAB4_SENDEDSMS).setContent(R.id.listViewSendedSMS));
		tabHost.addTab(tabHost.newTabSpec(TAB5_RECEIEDSMS).setIndicator(TAB5_RECEIEDSMS).setContent(R.id.listViewReceviedSMS));

		TabWidget tabWidget = tabHost.getTabWidget();
		for (int i = 0; i < tabWidget.getChildCount(); i++) {
			View child = tabWidget.getChildAt(i);
			final TextView tv = (TextView) child.findViewById(android.R.id.title);
			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tv.getLayoutParams();
			params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0); // 取消文字底边对
			params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); // 设置文字居中对齐
			// child.getLayoutParams().height = 25;
			tv.setTextColor(android.graphics.Color.GREEN);
		}

		tabHost.setOnTabChangedListener(new OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				// TODO Auto-generated method stub
				setCheckBoxIsInvisble();
			}
		});

		if (!(isServiceRunning(getApplicationContext(), "com.ericdm.callingandsmsstatistics.CallingAndSmsStatisticsService"))) {
			Intent intent_ = new Intent(MainActivity.this, CallingAndSmsStatisticsService.class);
			startService(intent_);
		}

		ExitApplication.getInstance().addActivity(this);
		
        gestureDetector = new GestureDetector(new MyGestureDetector());  
        gestureListener = new View.OnTouchListener() {  
            public boolean onTouch(View v, MotionEvent event) {  
                if (gestureDetector.onTouchEvent(event)) {  
                    return true;  
                }  
                return false;  
            }  
        }; 
	} // onCreate End
	
	OnClickListener callButtonListener =  new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"));
		    startActivity(intent);
		}
	};
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
        if (gestureDetector.onTouchEvent(ev)) {  
        	ev.setAction(MotionEvent.ACTION_CANCEL);  
        }  
		return super.dispatchTouchEvent(ev);
	}

	android.view.View.OnClickListener contactsButtonListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {	
			Intent intent = new Intent();   
			intent.setAction(Intent.ACTION_VIEW);   
			intent.setData(ContactsContract.Contacts.CONTENT_URI);   
			startActivity(intent);   
		}
	};

	OnClickListener deleteButtonListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String tabHostTagName = tabHost.getCurrentTabTag();
			ArrayList<String> selectedPhoneNumber = new ArrayList<String>();
			DatabaseOperator databaseOperator = new DatabaseOperator();
			if (tabHostTagName.equals(TAB2_OUTGOINGCALLS)) {
				selectedPhoneNumber = mListViewAdapterOutgoincCall.getSelectItems();
				for (int i = 0; i < selectedPhoneNumber.size(); i++) {
					databaseOperator.deleteRecord(DatabaseOperator.TABLE_NAME_OUGGOINGCALL, selectedPhoneNumber.get(i));
				}
			} else if (tabHostTagName.equals(TAB3_INCOMMINGCALLS)) {
				selectedPhoneNumber = mListViewAdapterIncommingCall.getSelectItems();
				for (int i = 0; i < selectedPhoneNumber.size(); i++) {
					databaseOperator.deleteRecord(DatabaseOperator.TABLE_NAME_INCOMINGCALL, selectedPhoneNumber.get(i));
				}
			}else if (tabHostTagName.equals(TAB4_SENDEDSMS)) {
				selectedPhoneNumber = mListViewAdapterSendedSms.getSelectItems();
				for (int i = 0; i < selectedPhoneNumber.size(); i++) {
					databaseOperator.deleteRecord(DatabaseOperator.TABLE_NAME_SENDEDSMS, selectedPhoneNumber.get(i));
				}
			}else if (tabHostTagName.equals(TAB5_RECEIEDSMS)) {
				selectedPhoneNumber = mListViewAdapterReceviedSms.getSelectItems();
				for (int i = 0; i < selectedPhoneNumber.size(); i++) {
					databaseOperator.deleteRecord(DatabaseOperator.TABLE_NAME_RECEVIEDSMS, selectedPhoneNumber.get(i));
				}
			}
			myHandler = new MyHanlder();
			QueryDataThreadWhenTimeChanged queryDataThreadWhenTimeChanged = new QueryDataThreadWhenTimeChanged();
			new Thread(queryDataThreadWhenTimeChanged).start();
			dialog.setTitle("检索数据");
			dialog.setMessage("数据更新中，请稍后");
			dialog.setIcon(android.R.drawable.ic_dialog_map);
			dialog.show();
		}
	};

	OnClickListener selectAllButtonListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String tabHostTagName = tabHost.getCurrentTabTag();
			if (tabHostTagName.equals(TAB2_OUTGOINGCALLS)) {
				mListViewAdapterOutgoincCall.selectAllItems();
				mListViewAdapterOutgoincCall.notifyDataSetChanged();
			} else if (tabHostTagName.equals(TAB3_INCOMMINGCALLS)) {
				mListViewAdapterIncommingCall.selectAllItems();
				mListViewAdapterIncommingCall.notifyDataSetChanged();
			}else if (tabHostTagName.equals(TAB4_SENDEDSMS)) {
				mListViewAdapterSendedSms.selectAllItems();
				mListViewAdapterSendedSms.notifyDataSetChanged();
			}else if (tabHostTagName.equals(TAB5_RECEIEDSMS)) {
				mListViewAdapterReceviedSms.selectAllItems();
				mListViewAdapterReceviedSms.notifyDataSetChanged();
			}
		}
	};

	OnClickListener deselectAllItemsListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String tabHostTagName = tabHost.getCurrentTabTag();
			if (tabHostTagName.equals(TAB2_OUTGOINGCALLS)) {
				mListViewAdapterOutgoincCall.deselectAllItems();
				mListViewAdapterOutgoincCall.notifyDataSetChanged();
			} else if (tabHostTagName.equals(TAB3_INCOMMINGCALLS)) {
				mListViewAdapterIncommingCall.deselectAllItems();
				mListViewAdapterIncommingCall.notifyDataSetChanged();
			}else if (tabHostTagName.equals(TAB4_SENDEDSMS)) {
				mListViewAdapterSendedSms.deselectAllItems();
				mListViewAdapterSendedSms.notifyDataSetChanged();
			}else if (tabHostTagName.equals(TAB5_RECEIEDSMS)) {
				mListViewAdapterReceviedSms.deselectAllItems();
				mListViewAdapterReceviedSms.notifyDataSetChanged();
			}
		}
	};

	OnClickListener inverseSelectedListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String tabHostTagName = tabHost.getCurrentTabTag();
			if (tabHostTagName.equals(TAB2_OUTGOINGCALLS)) {
				mListViewAdapterOutgoincCall.inverseSelectItems();
				mListViewAdapterOutgoincCall.notifyDataSetChanged();
			} else if (tabHostTagName.equals(TAB3_INCOMMINGCALLS)) {
				mListViewAdapterIncommingCall.inverseSelectItems();
				mListViewAdapterIncommingCall.notifyDataSetChanged();
			}else if (tabHostTagName.equals(TAB4_SENDEDSMS)) {
				mListViewAdapterSendedSms.inverseSelectItems();
				mListViewAdapterSendedSms.notifyDataSetChanged();
			}else if (tabHostTagName.equals(TAB5_RECEIEDSMS)) {
				mListViewAdapterReceviedSms.inverseSelectItems();
				mListViewAdapterReceviedSms.notifyDataSetChanged();
			}
		}
	};

	@SuppressLint("HandlerLeak")
	class MyHanlder extends Handler {
		@SuppressLint("HandlerLeak")
		public MyHanlder() {
		}

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			Bundle bundle = msg.getData();

			List<HashMap<String, String>> summaryList = new ArrayList<HashMap<String, String>>();
			summaryList = (List<HashMap<String, String>>) bundle.getSerializable("summaryList");
			setListViewData(summaryList);

			List<HashMap<String, String>> outgoingCallList_ = new ArrayList<HashMap<String, String>>();
			outgoingCallList_ = (List<HashMap<String, String>>) bundle.getSerializable("outgoingCallList");
			setoutgoingCallListViewData(outgoingCallList_);

			List<HashMap<String, String>> incomingCallList_ = new ArrayList<HashMap<String, String>>();
			incomingCallList_ = (List<HashMap<String, String>>) bundle.getSerializable("incomingCallList");
			setIncomingCallListViewData(incomingCallList_);

			List<HashMap<String, String>> ReceivedSMSList_ = new ArrayList<HashMap<String, String>>();
			ReceivedSMSList_ = (List<HashMap<String, String>>) bundle.getSerializable("recevidSMSList");
			setReceivedSMSListViewData(ReceivedSMSList_);

			List<HashMap<String, String>> sendedSMSList_ = new ArrayList<HashMap<String, String>>();
			sendedSMSList_ = (List<HashMap<String, String>>) bundle.getSerializable("sendedSMSList");
			setSendedSMSListViewData(sendedSMSList_);
			dialog.cancel();
		}
	}
	
	public void setListViewData(List<HashMap<String, String>> thelist) {
		listViewAll.setAdapter(new SimpleAdapter(this, thelist, R.layout.listviewlayout, new String[] { "summaryTime" }, new int[] { R.id.listViewTextContent }));
	}

	public void setSendedSMSListViewData(List<HashMap<String, String>> thelist) {
		ArrayList<String> phoneNumberList = new ArrayList<String>();
		ArrayList<String> callTimeList = new ArrayList<String>();

		for (int i = 0; i < thelist.size(); i++) {
			HashMap<String, String> content_1 = thelist.get(i);
			String content_2 = content_1.get("sendedSMS");
			int index = content_2.lastIndexOf("___");
			String phoneNumber = content_2.substring(0, index);
			String callTime = content_2.substring(index + 3, content_2.length());
			phoneNumberList.add(getContactNameByPhonenumber(phoneNumber));
			callTimeList.add(callTime);
		}
		
		mListViewAdapterSendedSms = new ListViewAdapterSendedSms(phoneNumberList, callTimeList, MainActivity.this);
		listViewSendedSMS.setAdapter(mListViewAdapterSendedSms);
	//	listViewSendedSMS.setAdapter(new SimpleAdapter(this, thelist, R.layout.listviewlayout, new String[] { "sendedSMS" }, new int[] { R.id.listViewTextContent }));
		listViewSendedSMS.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
				// TODO Auto-generated method stub
				menu.add(3, 0, 0, "呼叫此号码");
				menu.add(3, 1, 0, "发送短信");
				menu.add(3, 2, 0, "查看详细记录");
				menu.add(3, 3, 0, "删除此条记录");
				menu.add(3, 4, 0, "多选删除");
			}
		});
		
		listViewSendedSMS.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub

				ListViewAdapterSendedSms.ViewHolder holder = (ListViewAdapterSendedSms.ViewHolder) arg1.getTag();
				holder.cb.toggle();
				if (ListViewAdapterSendedSms.isItemSelected(arg2)) {
					ListViewAdapterSendedSms.getIsSelected().put(arg2, false);
				} else {
					ListViewAdapterSendedSms.getIsSelected().put(arg2, true);
				}
				if (!ListViewAdapterSendedSms.isShowCheckBox) {
					arg1.showContextMenu();
				}
				mListViewAdapterSendedSms.notifyDataSetChanged();
			}
		});
	}

	public void setReceivedSMSListViewData(List<HashMap<String, String>> thelist) {
		ArrayList<String> phoneNumberList = new ArrayList<String>();
		ArrayList<String> callTimeList = new ArrayList<String>();

		for (int i = 0; i < thelist.size(); i++) {
			HashMap<String, String> content_1 = thelist.get(i);
			String content_2 = content_1.get("receviedSMS");
			int index = content_2.lastIndexOf("___");
			String phoneNumber = content_2.substring(0, index);
			String callTime = content_2.substring(index + 3, content_2.length());
			phoneNumberList.add(getContactNameByPhonenumber(phoneNumber));
			callTimeList.add(callTime);
		}
		
		mListViewAdapterReceviedSms = new ListViewAdapterReceviedSms(phoneNumberList, callTimeList, MainActivity.this);
		listViewReceviedSMS.setAdapter(mListViewAdapterReceviedSms);
		//listViewReceviedSMS.setAdapter(new SimpleAdapter(this, thelist, R.layout.listviewlayout, new String[] { "receviedSMS" }, new int[] { R.id.listViewTextContent }));
		listViewReceviedSMS.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
				// TODO Auto-generated method stub
				menu.add(2, 0, 0, "呼叫此号码");
				menu.add(2, 1, 0, "发送短信");
				menu.add(2, 2, 0, "查看详细记录");
				menu.add(2, 3, 0, "删除此条记录");
				menu.add(2, 4, 0, "多选删除");
			}
		});
		
		listViewReceviedSMS.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub

				ListViewAdapterReceviedSms.ViewHolder holder = (ListViewAdapterReceviedSms.ViewHolder) arg1.getTag();
				holder.cb.toggle();
				if (ListViewAdapterReceviedSms.isItemSelected(arg2)) {
					ListViewAdapterReceviedSms.getIsSelected().put(arg2, false);
				} else {
					ListViewAdapterReceviedSms.getIsSelected().put(arg2, true);
				}
				if (!ListViewAdapterReceviedSms.isShowCheckBox) {
					arg1.showContextMenu();
				}
				mListViewAdapterReceviedSms.notifyDataSetChanged();
			}
		});
	}

	public void setIncomingCallListViewData(List<HashMap<String, String>> thelist) {
		//listViewIncommingCalls.setAdapter(new SimpleAdapter(this, thelist, R.layout.listviewlayout, new String[] { "incomingCallTime" }, new int[] { R.id.listViewTextContent }));
		ArrayList<String> phoneNumberList = new ArrayList<String>();
		ArrayList<String> callTimeList = new ArrayList<String>();

		for (int i = 0; i < thelist.size(); i++) {
			HashMap<String, String> content_1 = thelist.get(i);
			String content_2 = content_1.get("incomingCallTime");
			int index = content_2.lastIndexOf("___");
			String phoneNumber = content_2.substring(0, index);
			String callTime = content_2.substring(index + 3, content_2.length());
			phoneNumberList.add(getContactNameByPhonenumber(phoneNumber));
			callTimeList.add(callTime);
		}

		mListViewAdapterIncommingCall = new ListViewAdapterIncommingCall(phoneNumberList, callTimeList, MainActivity.this);
		listViewIncommingCalls.setAdapter(mListViewAdapterIncommingCall);

		listViewIncommingCalls.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
				// TODO Auto-generated method stub
				menu.add(1, 0, 0, "呼叫此号码");
				menu.add(1, 1, 0, "发送短信");
				menu.add(1, 2, 0, "查看详细记录");
				menu.add(1, 3, 0, "删除此条记录");
				menu.add(1, 4, 0, "多选删除");
			}
		});
		
		listViewIncommingCalls.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub

				ListViewAdapterIncommingCall.ViewHolder holder = (ListViewAdapterIncommingCall.ViewHolder) arg1.getTag();
				holder.cb.toggle();
				if (ListViewAdapterIncommingCall.isItemSelected(arg2)) {
					ListViewAdapterIncommingCall.getIsSelected().put(arg2, false);
				} else {
					ListViewAdapterIncommingCall.getIsSelected().put(arg2, true);
				}
				if (!ListViewAdapterIncommingCall.isShowCheckBox) {
					arg1.showContextMenu();
				}
				mListViewAdapterIncommingCall.notifyDataSetChanged();
			}
		});
	}

	public void setoutgoingCallListViewData(List<HashMap<String, String>> thelist) {
		ArrayList<String> phoneNumberList = new ArrayList<String>();
		ArrayList<String> callTimeList = new ArrayList<String>();

		for (int i = 0; i < thelist.size(); i++) {
			HashMap<String, String> content_1 = thelist.get(i);
			String content_2 = content_1.get("outgoingCallTime");
			int index = content_2.lastIndexOf("___");
			String phoneNumber = content_2.substring(0, index);
			String callTime = content_2.substring(index + 3, content_2.length());
			phoneNumberList.add(getContactNameByPhonenumber(phoneNumber));
			callTimeList.add(callTime);
		}
		mListViewAdapterOutgoincCall = new ListViewAdapterOutgoincCall(phoneNumberList, callTimeList, MainActivity.this);
		//mListViewWithCheckBoxAdapterOutgoingCall = new ListViewWithCheckBoxAdapter(phoneNumberList, callTimeList, MainActivity.this, ListViewWithCheckBoxAdapter.LISTNAME_OUTGOINGCALL);
		listViewOutgoingCalls.setAdapter(mListViewAdapterOutgoincCall);
		// listViewOutgoingCalls.setAdapter(new SimpleAdapter(this, thelist,R.layout.listviewlayout, new String[] { "outgoingCallTime" }, new int[] { R.id.listViewTextContent }));
		listViewOutgoingCalls.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
				// TODO Auto-generated method stub
				menu.add(0, 0, 0, "呼叫此号码");
				menu.add(0, 1, 0, "发送短信");
				menu.add(0, 2, 0, "查看详细记录");
				menu.add(0, 3, 0, "删除此条记录");
				menu.add(0, 4, 0, "多选删除");
			}
		});
		
		listViewOutgoingCalls.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub

				ListViewAdapterOutgoincCall.ViewHolder holder = (ListViewAdapterOutgoincCall.ViewHolder) arg1.getTag();
				holder.cb.toggle();
				if (ListViewAdapterOutgoincCall.isItemSelected(arg2)) {
					ListViewAdapterOutgoincCall.getIsSelected().put(arg2, false);
				} else {
					ListViewAdapterOutgoincCall.getIsSelected().put(arg2, true);
				}
				if (!ListViewAdapterOutgoincCall.isShowCheckBox) {
					arg1.showContextMenu();
				}
				mListViewAdapterOutgoincCall.notifyDataSetChanged();
			}
		});
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (ListViewAdapterIncommingCall.isShowCheckBox || ListViewAdapterOutgoincCall.isShowCheckBox || ListViewAdapterSendedSms.isShowCheckBox || ListViewAdapterReceviedSms.isShowCheckBox) {
			setCheckBoxIsInvisble();
			return;
		}
		super.onBackPressed();
	}

	private void notifyDataSetChangedListview() {
		mListViewAdapterOutgoincCall.notifyDataSetChanged();
		mListViewAdapterIncommingCall.notifyDataSetChanged();
		mListViewAdapterReceviedSms.notifyDataSetChanged();
		mListViewAdapterSendedSms.notifyDataSetChanged();
	}

	public void setCHeckBoxIsVisble() {
		startTime.setVisibility(View.INVISIBLE);
		endTime.setVisibility(View.INVISIBLE);
		setTimeButton.setVisibility(View.INVISIBLE);
		selectAllButton.setVisibility(View.VISIBLE);
		deleteSelectedButton.setVisibility(View.VISIBLE);
		inverseSelectedButton.setVisibility(View.VISIBLE);
		deselectButton.setVisibility(View.VISIBLE);
		mListViewAdapterOutgoincCall.deselectAllItems();
		mListViewAdapterIncommingCall.deselectAllItems();
		mListViewAdapterReceviedSms.deselectAllItems();
		mListViewAdapterSendedSms.deselectAllItems();
		contactsButton.setVisibility(View.INVISIBLE);
		callButton.setVisibility(View.INVISIBLE);
		notifyDataSetChangedListview();
	}

	public void setCheckBoxIsInvisble() {
		ListViewAdapterIncommingCall.isShowCheckBox = false;
		ListViewAdapterOutgoincCall.isShowCheckBox = false;
		ListViewAdapterSendedSms.isShowCheckBox = false;
		ListViewAdapterReceviedSms.isShowCheckBox = false;
		startTime.setVisibility(View.VISIBLE);
		endTime.setVisibility(View.VISIBLE);
		setTimeButton.setVisibility(View.VISIBLE);
		selectAllButton.setVisibility(View.INVISIBLE);
		deleteSelectedButton.setVisibility(View.INVISIBLE);
		inverseSelectedButton.setVisibility(View.INVISIBLE);
		deselectButton.setVisibility(View.INVISIBLE);
		contactsButton.setVisibility(View.VISIBLE);
		callButton.setVisibility(View.VISIBLE);
		notifyDataSetChangedListview();
	}
	
	private void editThenCallPhoneNumber(String phoneNumber){
		Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phoneNumber));
		startActivity(intent);
	}
	
	private void sendSms(String phoneNumber){
		Intent intent = new Intent(Intent.ACTION_SENDTO,Uri.parse("smsto:"+phoneNumber));
		startActivity(intent);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		int group = item.getGroupId();
		int itemId = item.getItemId();
		String phoneNumber = "";
		ContextMenuInfo info = item.getMenuInfo();
		AdapterView.AdapterContextMenuInfo contextMenuInfo = (AdapterContextMenuInfo) info;
		int position = contextMenuInfo.position;
		if (group == 0) { // Outgoing Call
			String content = (String) listViewOutgoingCalls.getItemAtPosition(position);
			phoneNumber = getphoneNumberFormContactName(content);
			if (itemId == 0) { //呼叫号码
				editThenCallPhoneNumber(phoneNumber);
			}
			if (itemId == 1) { //发送短信
				sendSms(phoneNumber);
			}
			if (itemId == 2) { //查看详细记录
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, PhoneDetailInfoActivity.class);
				intent.putExtra("phoneNumber", phoneNumber);
				intent.putExtra("tableName", DatabaseOperator.TABLE_NAME_OUGGOINGCALL);
				intent.putExtra("startTime", queryTime_Start);
				intent.putExtra("endTime", queryTime_End);
				startActivity(intent);
			}
			if (itemId == 3) { //删除这个记录
				DatabaseOperator databaseOperator = new DatabaseOperator();
				databaseOperator.deleteRecord(DatabaseOperator.TABLE_NAME_OUGGOINGCALL, phoneNumber);
				myHandler = new MyHanlder();
				QueryDataThreadWhenTimeChanged queryDataThreadWhenTimeChanged = new QueryDataThreadWhenTimeChanged();
				new Thread(queryDataThreadWhenTimeChanged).start();
				dialog.setTitle("检索数据");
				dialog.setMessage("数据更新中，请稍后");
				dialog.setIcon(android.R.drawable.ic_dialog_map);
				dialog.show();
			}
			if (itemId == 4) { //多选删除
				if (ListViewAdapterOutgoincCall.isShowCheckBox) {
					ListViewAdapterOutgoincCall.isShowCheckBox = false;
					setCheckBoxIsInvisble();
				} else {
					ListViewAdapterOutgoincCall.isShowCheckBox = true;
					setCHeckBoxIsVisble();
				}
			}
		} else if (group == 1) { // Incomming Call
			String content = (String) listViewIncommingCalls.getItemAtPosition(position);
			phoneNumber = getphoneNumberFormContactName(content);
			if (itemId == 0) { //呼叫号码
				editThenCallPhoneNumber(phoneNumber);
			}
			if (itemId == 1) { //发送短信
				sendSms(phoneNumber);
			}
			if (itemId == 2) { //查看详细记录
				Intent intent = new Intent(); 
				intent.setClass(MainActivity.this,PhoneDetailInfoActivity.class); 
				intent.putExtra("phoneNumber",phoneNumber); 
				intent.putExtra("tableName",DatabaseOperator.TABLE_NAME_INCOMINGCALL);
				intent.putExtra("startTime", queryTime_Start);
				intent.putExtra("endTime", queryTime_End); 
				startActivity(intent);
			}
			if (itemId == 3) { //删除这个记录
				DatabaseOperator databaseOperator = new DatabaseOperator();
				databaseOperator.deleteRecord(DatabaseOperator.TABLE_NAME_INCOMINGCALL, phoneNumber);
				myHandler = new MyHanlder();
				QueryDataThreadWhenTimeChanged queryDataThreadWhenTimeChanged = new QueryDataThreadWhenTimeChanged();
				new Thread(queryDataThreadWhenTimeChanged).start();
				dialog.setTitle("检索数据");
				dialog.setMessage("数据更新中，请稍后");
				dialog.setIcon(android.R.drawable.ic_dialog_map);
				dialog.show();
			}
			if (itemId == 4) { //多选删除
				if (ListViewAdapterIncommingCall.isShowCheckBox) {
					ListViewAdapterIncommingCall.isShowCheckBox = false;
					setCheckBoxIsInvisble();
				} else {
					ListViewAdapterIncommingCall.isShowCheckBox = true;
					setCHeckBoxIsVisble();
				}
			}
		} else if (group == 2) {
			String content = (String) listViewReceviedSMS.getItemAtPosition(position);
			phoneNumber = getphoneNumberFormContactName(content);
			if (itemId == 0) { //呼叫号码
				editThenCallPhoneNumber(phoneNumber);
			}
			if (itemId == 1) { //发送短信
				sendSms(phoneNumber);
			}
			if (itemId == 2) { //查看详细记录
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, PhoneDetailInfoActivity.class);
				System.out.println("="+phoneNumber+"=");
				intent.putExtra("phoneNumber", phoneNumber);
				intent.putExtra("tableName", DatabaseOperator.TABLE_NAME_RECEVIEDSMS);
				intent.putExtra("startTime", queryTime_Start);
				intent.putExtra("endTime", queryTime_End);
				startActivity(intent);
			}
			if (itemId == 3) { //删除这个记录
				DatabaseOperator databaseOperator = new DatabaseOperator();
				databaseOperator.deleteRecord(DatabaseOperator.TABLE_NAME_RECEVIEDSMS, phoneNumber);
				myHandler = new MyHanlder();
				QueryDataThreadWhenTimeChanged queryDataThreadWhenTimeChanged = new QueryDataThreadWhenTimeChanged();
				new Thread(queryDataThreadWhenTimeChanged).start();
				dialog.setTitle("检索数据");
				dialog.setMessage("数据更新中，请稍后");
				dialog.setIcon(android.R.drawable.ic_dialog_map);
				dialog.show();
			}
			if (itemId == 4) { //多选删除
				if (ListViewAdapterReceviedSms.isShowCheckBox) {
					ListViewAdapterReceviedSms.isShowCheckBox = false;
					setCheckBoxIsInvisble();
				} else {
					ListViewAdapterReceviedSms.isShowCheckBox = true;
					setCHeckBoxIsVisble();
				}
			}
		} else if (group == 3) {
			String content = (String) listViewSendedSMS.getItemAtPosition(position);
			phoneNumber = getphoneNumberFormContactName(content);
			if (itemId == 0) { //呼叫号码
				editThenCallPhoneNumber(phoneNumber);
			}
			if (itemId == 1) { //发送短信
				sendSms(phoneNumber);
			}
			if (itemId == 2) { //查看详细记录
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, PhoneDetailInfoActivity.class);
				intent.putExtra("phoneNumber", phoneNumber);
				intent.putExtra("tableName", DatabaseOperator.TABLE_NAME_SENDEDSMS);
				intent.putExtra("startTime", queryTime_Start);
				intent.putExtra("endTime", queryTime_End);
				startActivity(intent);
			}
			if (itemId == 3) { //删除这个记录
				DatabaseOperator databaseOperator = new DatabaseOperator();
				databaseOperator.deleteRecord(DatabaseOperator.TABLE_NAME_SENDEDSMS, phoneNumber);
				myHandler = new MyHanlder();
				QueryDataThreadWhenTimeChanged queryDataThreadWhenTimeChanged = new QueryDataThreadWhenTimeChanged();
				new Thread(queryDataThreadWhenTimeChanged).start();
				dialog.setTitle("检索数据");
				dialog.setMessage("数据更新中，请稍后");
				dialog.setIcon(android.R.drawable.ic_dialog_map);
				dialog.show();
			}
			if (itemId == 4) { //多选删除
				if (ListViewAdapterSendedSms.isShowCheckBox) {
					ListViewAdapterSendedSms.isShowCheckBox = false;
					setCheckBoxIsInvisble();
				} else {
					ListViewAdapterSendedSms.isShowCheckBox = true;
					setCHeckBoxIsVisble();
				}
			}
		}
		return super.onContextItemSelected(item);
	}

	public String getPhoneNumberFormListView(String phoneNumber) {
		int betginIndex = phoneNumber.lastIndexOf("(");
		int endIndex = phoneNumber.lastIndexOf(")");
		return phoneNumber.substring(betginIndex + 1, endIndex);
	}
	
	class QueryDataThreadWhenTimeChanged implements Runnable{
		List<HashMap<String, String>> summaryList = new ArrayList<HashMap<String, String>>();
		List<HashMap<String, String>> outgoingCallList = new ArrayList<HashMap<String, String>>();
		List<HashMap<String, String>> incomingCallList = new ArrayList<HashMap<String, String>>();
		List<HashMap<String, String>> receviedSMSList = new ArrayList<HashMap<String, String>>();
		List<HashMap<String, String>> sendedSMSList = new ArrayList<HashMap<String, String>>();		

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			Bundle bundle = new Bundle();			
			incomingCallList = getIncomingCallTabviewDataWhenTimeChanged(queryTime_Start, queryTime_End);
			bundle.putSerializable("incomingCallList", (Serializable) incomingCallList);			
			summaryList = getSummaryTabviewDataWhenTimeChanged(queryTime_Start, queryTime_End);
			bundle.putSerializable("summaryList", (Serializable) summaryList);
			outgoingCallList = getOutGoingCallTabviewDataWhenTimeChanged(queryTime_Start, queryTime_End);
			bundle.putSerializable("outgoingCallList", (Serializable) outgoingCallList);			
			receviedSMSList = getReceiveSMSTabviewData(queryTime_Start, queryTime_End);
			bundle.putSerializable("recevidSMSList", (Serializable) receviedSMSList);
			sendedSMSList = getSendedSMSTabviewData(queryTime_Start, queryTime_End);
			bundle.putSerializable("sendedSMSList", (Serializable) sendedSMSList);
			msg.setData(bundle);
			MainActivity.this.myHandler.sendMessage(msg);
		}
	}

	class QueryDataThread implements Runnable {
		List<HashMap<String, String>> summaryList = new ArrayList<HashMap<String, String>>();
		List<HashMap<String, String>> outgoingCallList = new ArrayList<HashMap<String, String>>();
		List<HashMap<String, String>> incomingCallList = new ArrayList<HashMap<String, String>>();
		List<HashMap<String, String>> receviedSMSList = new ArrayList<HashMap<String, String>>();
		List<HashMap<String, String>> sendedSMSList = new ArrayList<HashMap<String, String>>();

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			Bundle bundle = new Bundle();
			summaryList = getSummaryTabviewData(queryTime_Start, queryTime_End);
			bundle.putSerializable("summaryList", (Serializable) summaryList);
			outgoingCallList = getOutGoingCallTabviewData(queryTime_Start, queryTime_End);
			bundle.putSerializable("outgoingCallList", (Serializable) outgoingCallList);
			incomingCallList = getIncomingCallTabviewData(queryTime_Start, queryTime_End);
			bundle.putSerializable("incomingCallList", (Serializable) incomingCallList);
			receviedSMSList = getReceiveSMSTabviewData(queryTime_Start, queryTime_End);
			bundle.putSerializable("recevidSMSList", (Serializable) receviedSMSList);
			sendedSMSList = getSendedSMSTabviewData(queryTime_Start, queryTime_End);
			bundle.putSerializable("sendedSMSList", (Serializable) sendedSMSList);
			msg.setData(bundle);
			MainActivity.this.myHandler.sendMessage(msg);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (!(isServiceRunning(getApplicationContext(), "com.ericdm.callingandsmsstatistics.CallingAndSmsStatisticsService"))) {
			Intent intent_ = new Intent(MainActivity.this, CallingAndSmsStatisticsService.class);
			startService(intent_);
		}

		super.onResume();
		myHandler = new MyHanlder();
		QueryDataThread queryDataThread = new QueryDataThread();
		new Thread(queryDataThread).start();
	}

	public String getContactNameByPhonenumber(String phonenumber) {
		String name = "";
		String phoneNumber_ = phonenumber.replace(" ", "");
		String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER };
		Cursor cursor = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
		if (cursor == null) {
			return phonenumber;
		}
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			int phoneFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
			String number_ = cursor.getString(phoneFieldColumnIndex);
			if (number_.replace(" ", "").equals(phoneNumber_)) {
				int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
				name = cursor.getString(nameFieldColumnIndex);
				cursor.close();
				return name;
			}
		}
		cursor.close();
		return phonenumber;
	}

	public String getphoneNumberFormContactName(String contactName) {
		String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER };
		Cursor cursor = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
		if (cursor == null) {
			return contactName; // This is the phone number.
		}
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
			String name = cursor.getString(nameFieldColumnIndex);
			if (contactName.equals(name)) {
				int phoneFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
				String number_ = cursor.getString(phoneFieldColumnIndex);
				cursor.close();
				return number_;
			}
		}
		return contactName;
	}

	public List<HashMap<String, String>> getSendedSMSTabviewData(String startTime, String endTime) {
		ContentValues values = new ContentValues();
		values.clear();
		DatabaseHelper databaseHelper = new DatabaseHelper(MainApplication.getContext(), "CallingHistoryDatabase");
		SQLiteDatabase sqLiteDatabase = databaseHelper.getReadableDatabase();
		List<HashMap<String, String>> list_ = new ArrayList<HashMap<String, String>>();
		List<String> phoneNumberList = new ArrayList<String>();
		Cursor cursor = sqLiteDatabase.query(DatabaseOperator.TABLE_NAME_SENDEDSMS, new String[] { "PHONENUMBER", "SENDED_SMS", "DATE_" }, null, null, null, null, null);
		while (cursor.moveToNext()) {
			String date = cursor.getString(cursor.getColumnIndex("DATE_"));
			if ((date.compareTo(startTime) >= 0) && (date.compareTo(endTime) <= 0)) {
				String phoneNumber = cursor.getString(cursor.getColumnIndex("PHONENUMBER"));
				phoneNumberList.add(phoneNumber);
			}
		}
		HashSet<String> hashSet = new HashSet<String>(phoneNumberList);
		phoneNumberList.clear();
		phoneNumberList.addAll(hashSet);
		for (int i = 0; i < phoneNumberList.size(); i++) {
			String currentPhoneNumber = phoneNumberList.get(i);
			Cursor cursor1 = sqLiteDatabase.query(DatabaseOperator.TABLE_NAME_SENDEDSMS, new String[] { "PHONENUMBER", "SENDED_SMS", "DATE_" }, "PHONENUMBER=?", new String[] { currentPhoneNumber }, null, null, null);
			String queryedData = "";
			int queryedData_ = 0;
			while (cursor1.moveToNext()) {
				queryedData = cursor1.getString(cursor1.getColumnIndex("SENDED_SMS"));
				queryedData_ = queryedData_ + Integer.parseInt(queryedData);
			}
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("sendedSMS", currentPhoneNumber + "___" +queryedData_);
			//hashMap.put("sendedSMS", getContactNameByPhonenumber(currentPhoneNumber) + "(" + currentPhoneNumber + ")" + " : " + queryedData_);
			list_.add(hashMap);
			cursor1.close();
		}
		cursor.close();
		sqLiteDatabase.close();
		return list_;
	}

	public List<HashMap<String, String>> getReceiveSMSTabviewData(String startTime, String endTime) {
		ContentValues values = new ContentValues();
		values.clear();
		DatabaseHelper databaseHelper = new DatabaseHelper(MainApplication.getContext(), "CallingHistoryDatabase");
		SQLiteDatabase sqLiteDatabase = databaseHelper.getReadableDatabase();
		List<HashMap<String, String>> list_ = new ArrayList<HashMap<String, String>>();
		List<String> phoneNumberList = new ArrayList<String>();
		Cursor cursor = sqLiteDatabase.query(DatabaseOperator.TABLE_NAME_RECEVIEDSMS, new String[] { "PHONENUMBER", "RECEVIED_SMS", "DATE_" }, null, null, null, null, null);
		while (cursor.moveToNext()) {
			String date = cursor.getString(cursor.getColumnIndex("DATE_"));
			if ((date.compareTo(startTime) >= 0) && (date.compareTo(endTime) <= 0)) {
				String phoneNumber = cursor.getString(cursor.getColumnIndex("PHONENUMBER"));
				phoneNumberList.add(phoneNumber);
			}
		}
		HashSet<String> hashSet = new HashSet<String>(phoneNumberList);
		phoneNumberList.clear();
		phoneNumberList.addAll(hashSet);
		for (int i = 0; i < phoneNumberList.size(); i++) {
			String currentPhoneNumber = phoneNumberList.get(i);
			Cursor cursor1 = sqLiteDatabase.query(DatabaseOperator.TABLE_NAME_RECEVIEDSMS, new String[] { "PHONENUMBER", "RECEVIED_SMS", "DATE_" }, "PHONENUMBER=?", new String[] { currentPhoneNumber }, null, null, null);
			String queryedData = "";
			int queryedData_ = 0;
			while (cursor1.moveToNext()) {
				queryedData = cursor1.getString(cursor1.getColumnIndex("RECEVIED_SMS"));
				queryedData_ = queryedData_ + Integer.parseInt(queryedData);
			}
			HashMap<String, String> hashMap = new HashMap<String, String>();
			//hashMap.put("receviedSMS", getContactNameByPhonenumber(currentPhoneNumber) + "(" + currentPhoneNumber + ")" + " : " + queryedData_);
			hashMap.put("receviedSMS", currentPhoneNumber + "___" +queryedData_);
			list_.add(hashMap);
			cursor1.close();
		}
		cursor.close();
		sqLiteDatabase.close();
		return list_;
	}
	
	public List<HashMap<String, String>> getIncomingCallTabviewDataWhenTimeChanged(String startTime, String endTime) {
		DatabaseHelper databaseHelper = new DatabaseHelper(MainApplication.getContext(), "CallingHistoryDatabase");
		SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
		sqLiteDatabase.execSQL("DROP TABLE IF EXISTS CallingAndSmsHistoryTablePHONENUMBERINCOMING");
		sqLiteDatabase.execSQL(DatabaseHelper.CREATETABLESQL_PHONENUMBERINCOMING);		
		List<HashMap<String, String>> list_ = new ArrayList<HashMap<String, String>>();
		ContentValues values = new ContentValues();
		List<String> phoneNumberList = new ArrayList<String>();
		Cursor cursor = sqLiteDatabase.query(DatabaseOperator.TABLE_NAME_INCOMINGCALL, new String[] { "PHONENUMBER", "INCOMMING_CALL", "DATE_" }, null, null, null, null, null);
		while (cursor.moveToNext()) {
			String date = cursor.getString(cursor.getColumnIndex("DATE_"));
			if ((date.compareTo(startTime) >= 0) && (date.compareTo(endTime) <= 0)) {
				String phoneNumber = cursor.getString(cursor.getColumnIndex("PHONENUMBER"));
				phoneNumberList.add(phoneNumber);
			}
		}
		HashSet<String> hashSet = new HashSet<String>(phoneNumberList);
		phoneNumberList.clear();
		phoneNumberList.addAll(hashSet);
		for (int i = 0; i < phoneNumberList.size(); i++) {
			String currentPhoneNumber = phoneNumberList.get(i);
			Cursor cursor1 = sqLiteDatabase.query(DatabaseOperator.TABLE_NAME_INCOMINGCALL, new String[] { "PHONENUMBER", "INCOMMING_CALL", "DATE_" }, "PHONENUMBER=?", new String[] { currentPhoneNumber }, null, null, null);
			String queryedData = "";
			int queryedData_ = 0;
			while (cursor1.moveToNext()) {
				queryedData = cursor1.getString(cursor1.getColumnIndex("INCOMMING_CALL"));
				queryedData_ = queryedData_ + Integer.parseInt(queryedData);
			}
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("incomingCallTime", currentPhoneNumber + "___" + secondToMinutes(queryedData_));
			list_.add(hashMap);
			cursor1.close();
			values.clear();
			values.put("PHONENUMBER", currentPhoneNumber);
			values.put("PHONEINCOMINGTIME", queryedData_);
			sqLiteDatabase.insert("CallingAndSmsHistoryTablePHONENUMBERINCOMING", null, values);
		}
		cursor.close();
		sqLiteDatabase.close();
		return list_;
	}

	public List<HashMap<String, String>> getIncomingCallTabviewData(String startTime, String endTime) {
		List<HashMap<String, String>> list_ = new ArrayList<HashMap<String, String>>();
		DatabaseHelper databaseHelper = new DatabaseHelper(MainApplication.getContext(), "CallingHistoryDatabase");
		SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
		String phone;
		int callTime = 0;
		Cursor cursor = sqLiteDatabase.query("CallingAndSmsHistoryTablePHONENUMBERINCOMING", new String[] { "PHONENUMBER", "PHONEINCOMINGTIME"}, null, null, null, null, null);
		while (cursor.moveToNext())  
		{
			phone = cursor.getString(cursor.getColumnIndex("PHONENUMBER")); 
			if (phone == null) 
			{
				cursor.close();
				sqLiteDatabase.close();
			}
			callTime = cursor.getInt(cursor.getColumnIndex("PHONEINCOMINGTIME"));
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("incomingCallTime", phone + "___" + secondToMinutes(callTime));
			list_.add(hashMap);	
		}
		cursor.close();
		sqLiteDatabase.close();
		return list_;
	}
	
	public List<HashMap<String, String>> getOutGoingCallTabviewDataWhenTimeChanged(String startTime, String endTime){
		ContentValues values = new ContentValues();
		DatabaseHelper databaseHelper = new DatabaseHelper(MainApplication.getContext(), "CallingHistoryDatabase");
		SQLiteDatabase sqLiteDatabase = databaseHelper.getReadableDatabase();
		sqLiteDatabase.execSQL("DROP TABLE IF EXISTS CallingAndSmsHistoryTablePHONENUMBEROUTGOING");
		sqLiteDatabase.execSQL(DatabaseHelper.CREATETABLESQL_PHONENUMBEROUTGOING);		
		List<HashMap<String, String>> list_ = new ArrayList<HashMap<String, String>>();
		List<String> phoneNumberList = new ArrayList<String>();
		Cursor cursor = sqLiteDatabase.query("CallingAndSmsHistoryTableOUTGOINGCALL", new String[] { "PHONENUMBER", "OUT_GOING_CALL", "DATE_" }, null, null, null, null, null);
		while (cursor.moveToNext()) {
			String date = cursor.getString(cursor.getColumnIndex("DATE_"));
			if ((date.compareTo(startTime) >= 0) && (date.compareTo(endTime) <= 0)) {
				String phoneNumber = cursor.getString(cursor.getColumnIndex("PHONENUMBER"));
				phoneNumberList.add(phoneNumber);
			}
		}
		HashSet<String> hashSet = new HashSet<String>(phoneNumberList);
		phoneNumberList.clear();
		phoneNumberList.addAll(hashSet);
		for (int i = 0; i < phoneNumberList.size(); i++) {
			String currentPhoneNumber = phoneNumberList.get(i);
			Cursor cursor1 = sqLiteDatabase.query("CallingAndSmsHistoryTableOUTGOINGCALL", new String[] { "PHONENUMBER", "OUT_GOING_CALL", "DATE_" }, "PHONENUMBER=?", new String[] { currentPhoneNumber }, null, null, null);
			String queryedData = "";
			int queryedData_ = 0;
			while (cursor1.moveToNext()) {
				queryedData = cursor1.getString(cursor1.getColumnIndex("OUT_GOING_CALL"));
				queryedData_ = queryedData_ + Integer.parseInt(queryedData);
			}
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("outgoingCallTime", currentPhoneNumber + "___" + secondToMinutes(queryedData_));
			list_.add(hashMap);
			cursor1.close();
			values.clear();
			values.put("PHONENUMBER", currentPhoneNumber);
			values.put("PHONEOUTGOINGTIME", queryedData_);
			sqLiteDatabase.insert("CallingAndSmsHistoryTablePHONENUMBEROUTGOING", null, values);
		}
		cursor.close();
		sqLiteDatabase.close();
		return list_;
	}

	public List<HashMap<String, String>> getOutGoingCallTabviewData(String startTime, String endTime) {
		List<HashMap<String, String>> list_ = new ArrayList<HashMap<String, String>>();
		DatabaseHelper databaseHelper = new DatabaseHelper(MainApplication.getContext(), "CallingHistoryDatabase");
		SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
		String phone;
		int callTime = 0;
		Cursor cursor = sqLiteDatabase.query("CallingAndSmsHistoryTablePHONENUMBEROUTGOING", new String[] { "PHONENUMBER", "PHONEOUTGOINGTIME"}, null, null, null, null, null);
		while (cursor.moveToNext())  
		{
			phone = cursor.getString(cursor.getColumnIndex("PHONENUMBER")); 
			if (phone == null) 
			{
				cursor.close();
				sqLiteDatabase.close();
			}
			callTime = cursor.getInt(cursor.getColumnIndex("PHONEOUTGOINGTIME"));
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("outgoingCallTime", phone + "___" + secondToMinutes(callTime));
			list_.add(hashMap);	
		}
		cursor.close();
		sqLiteDatabase.close();
		return list_;
	}
	
	public List<HashMap<String, String>> getSummaryTabviewDataWhenTimeChanged(String startTime, String endTime) {
		ContentValues values = new ContentValues();
		DatabaseHelper databaseHelper = new DatabaseHelper(MainApplication.getContext(), "CallingHistoryDatabase");
		SQLiteDatabase sqLiteDatabase = databaseHelper.getReadableDatabase();
		List<HashMap<String, String>> summaryList = new ArrayList<HashMap<String, String>>();
		
		int allIncomingCallTime = 0;
		Cursor cursor1 = sqLiteDatabase.query("CallingAndSmsHistoryTableINCOMINGCALL", new String[] { "PHONENUMBER", "INCOMMING_CALL", "DATE_" }, null, null, null, null, null);
		while (cursor1.moveToNext()) {
			String date = cursor1.getString(cursor1.getColumnIndex("DATE_"));
			if ((date.compareTo(startTime) >= 0) && (date.compareTo(endTime) <= 0)) {
				String queryedData = cursor1.getString(cursor1.getColumnIndex("INCOMMING_CALL"));
				int queryedData_ = Integer.parseInt(queryedData);
				allIncomingCallTime = allIncomingCallTime + queryedData_;
			}
		}
		HashMap<String, String> hashMap_incommingCall = new HashMap<String, String>();
		hashMap_incommingCall.put("summaryTime", "接听电话总时间：   " + secondToMinutes(allIncomingCallTime));
		summaryList.add(hashMap_incommingCall);
		values.clear();
		values.put("SUM_INCOMING", allIncomingCallTime);
		int row1 = sqLiteDatabase.update("CallingAndSmsHistoryTableSUMINCOMING", values, null,null);
		if (row1 == 0) {
			sqLiteDatabase.insert("CallingAndSmsHistoryTableSUMINCOMING", null, values);
		}
		
		int alloutgoingCallTime = 0;
		Cursor cursor2 = sqLiteDatabase.query("CallingAndSmsHistoryTableOUTGOINGCALL", new String[] { "PHONENUMBER", "OUT_GOING_CALL", "DATE_" }, null, null, null, null, null);
		while (cursor2.moveToNext()) {
			String date = cursor2.getString(cursor2.getColumnIndex("DATE_"));
			if ((date.compareTo(startTime) >= 0) && (date.compareTo(endTime) <= 0)) {
				String queryedData = cursor2.getString(cursor2.getColumnIndex("OUT_GOING_CALL"));
				int queryedData_ = Integer.parseInt(queryedData);
				alloutgoingCallTime = alloutgoingCallTime + queryedData_;
			}
		}
		HashMap<String, String> hashMap_outgoingCall = new HashMap<String, String>();
		hashMap_outgoingCall.put("summaryTime", "拨打电话总时间：   " + secondToMinutes(alloutgoingCallTime));
		summaryList.add(hashMap_outgoingCall);
		values.clear();
		values.put("SUM_OUTGOING", alloutgoingCallTime);
		int row2 = sqLiteDatabase.update("CallingAndSmsHistoryTableSUMOUTGOING", values, null,null);
		if (row2 == 0) {
			sqLiteDatabase.insert("CallingAndSmsHistoryTableSUMOUTGOING", null, values);
		}	

		int allReceviedsms = 0;
		Cursor cursor3 = sqLiteDatabase.query("CallingAndSmsHistoryTableRECEVIEDSMS", new String[] { "PHONENUMBER", "RECEVIED_SMS", "DATE_" }, null, null, null, null, null);
		while (cursor3.moveToNext()) {
			String date = cursor3.getString(cursor3.getColumnIndex("DATE_"));
			if ((date.compareTo(startTime) >= 0) && (date.compareTo(endTime) <= 0)) {
				String queryedData = cursor3.getString(cursor3.getColumnIndex("RECEVIED_SMS"));
				int queryedData_ = Integer.parseInt(queryedData);
				allReceviedsms = allReceviedsms + queryedData_;
			}
		}
		HashMap<String, String> hashMap_receviedSms = new HashMap<String, String>();
		hashMap_receviedSms.put("summaryTime", "接收短息总个数：   " + allReceviedsms);
		summaryList.add(hashMap_receviedSms);
		values.clear();
		values.put("SUM_RECEIVESMS", allReceviedsms);
		int row3 = sqLiteDatabase.update("CallingAndSmsHistoryTableSUMRECEIVESMS", values, null,null);
		if (row3 == 0) {
			sqLiteDatabase.insert("CallingAndSmsHistoryTableSUMRECEIVESMS", null, values);
		}	
		

		int allSendedSms = 0;
		Cursor cursor4 = sqLiteDatabase.query("CallingAndSmsHistoryTableSENDEDSMS", new String[] { "PHONENUMBER", "SENDED_SMS", "DATE_" }, null, null, null, null, null);
		while (cursor4.moveToNext()) {
			String date = cursor4.getString(cursor4.getColumnIndex("DATE_"));
			if ((date.compareTo(startTime) >= 0) && (date.compareTo(endTime) <= 0)) {
				String queryedData = cursor4.getString(cursor4.getColumnIndex("SENDED_SMS"));
				int queryedData_ = Integer.parseInt(queryedData);
				allSendedSms = allSendedSms + queryedData_;
			}
		}
		HashMap<String, String> hashMap_sendedSms = new HashMap<String, String>();
		hashMap_sendedSms.put("summaryTime", "发送短息总个数：   " + allSendedSms);
		summaryList.add(hashMap_sendedSms);
		values.clear();
		values.put("SUM_SENDSMS", allSendedSms);
		int row4 = sqLiteDatabase.update("CallingAndSmsHistoryTableSUMSENDSMS", values, null,null);
		if (row4 == 0) {
			sqLiteDatabase.insert("CallingAndSmsHistoryTableSUMSENDSMS", null, values);
		}	
		cursor1.close();
		cursor2.close();
		cursor3.close();
		cursor4.close();
		sqLiteDatabase.close();
		return summaryList;
	}
	
	public List<HashMap<String, String>> getSummaryTabviewData(String startTime, String endTime) {
		ContentValues values = new ContentValues();
		values.clear();
		DatabaseHelper databaseHelper = new DatabaseHelper(MainApplication.getContext(), "CallingHistoryDatabase");
		SQLiteDatabase sqLiteDatabase = databaseHelper.getReadableDatabase();
		List<HashMap<String, String>> summaryList = new ArrayList<HashMap<String, String>>();
		
		int allIncomingCallTime = 0;
		Cursor cursor1 = sqLiteDatabase.query("CallingAndSmsHistoryTableSUMINCOMING", new String[] {"SUM_INCOMING"}, null, null, null, null, null);
		while (cursor1.moveToNext()) {
			allIncomingCallTime = cursor1.getInt(cursor1.getColumnIndex("SUM_INCOMING"));
		}
		HashMap<String, String> hashMap_incommingCall = new HashMap<String, String>();
		hashMap_incommingCall.put("summaryTime", "接听电话总时间：   " + secondToMinutes(allIncomingCallTime));
		summaryList.add(hashMap_incommingCall);		

		int alloutgoingCallTime = 0;
		Cursor cursor2 = sqLiteDatabase.query("CallingAndSmsHistoryTableSUMOUTGOING", new String[] {"SUM_OUTGOING"}, null, null, null, null, null);
		while (cursor2.moveToNext()) {
			alloutgoingCallTime = cursor2.getInt(cursor2.getColumnIndex("SUM_OUTGOING"));
		}
		HashMap<String, String> hashMap_outgoingCall = new HashMap<String, String>();
		hashMap_outgoingCall.put("summaryTime", "拨打电话总时间：   " + secondToMinutes(alloutgoingCallTime));
		summaryList.add(hashMap_outgoingCall);

		int allReceviedsms = 0;
		Cursor cursor3 = sqLiteDatabase.query("CallingAndSmsHistoryTableSUMRECEIVESMS", new String[] {"SUM_RECEIVESMS"}, null, null, null, null, null);
		while (cursor3.moveToNext()) {
			allReceviedsms = cursor3.getInt(cursor3.getColumnIndex("SUM_RECEIVESMS"));
		}
		HashMap<String, String> hashMap_receviedSms = new HashMap<String, String>();
		hashMap_receviedSms.put("summaryTime", "接收短息总个数：   " + allReceviedsms);
		summaryList.add(hashMap_receviedSms);

		int allSendedSms = 0;
		Cursor cursor4 = sqLiteDatabase.query("CallingAndSmsHistoryTableSUMSENDSMS", new String[] {"SUM_SENDSMS"}, null, null, null, null, null);
		while (cursor4.moveToNext()) {
			allSendedSms = cursor4.getInt(cursor4.getColumnIndex("SUM_SENDSMS"));
		}
		HashMap<String, String> hashMap_sendedSms = new HashMap<String, String>();
		hashMap_sendedSms.put("summaryTime", "发送短息总个数：   " + allSendedSms);
		summaryList.add(hashMap_sendedSms);
		cursor1.close();
		cursor2.close();
		cursor3.close();
		cursor4.close();
		sqLiteDatabase.close();
		return summaryList;
	}

	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> setviceList = activityManager.getRunningServices(30);
		if (!(setviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < setviceList.size(); i++) {
			if (setviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_settings:
			ExitApplication.getInstance().exit();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public boolean isLeapYear(int theYear) {
		boolean isLeap = false;
		if (theYear % 4 == 0 && (theYear % 100) != 0) {
			leap = true;
		} else if (theYear % 400 == 0) {
			leap = false;
		}
		return isLeap;
	}

	OnClickListener changeTimeButonListener = new OnClickListener() {
		@SuppressWarnings("deprecation")
		@Override
		public void onClick(View v) {
			final AlertDialog dlg = new AlertDialog.Builder(MainActivity.this).create();
			dlg.show();
			dlg.getWindow().setContentView(R.layout.set_time_layout);
			dlg.getWindow().setGravity(Gravity.CENTER);
			dlg.getWindow().setLayout(android.view.WindowManager.LayoutParams.FILL_PARENT, android.view.WindowManager.LayoutParams.WRAP_CONTENT);
			dlg.getWindow().setContentView(getLayoutInflater().inflate(R.layout.set_time_layout, null));
			Window window = dlg.getWindow();
			window.setContentView(R.layout.set_time_layout);
			noButton = (Button) window.findViewById(R.id._no);
			setStartTimeButton = (Button) window.findViewById(R.id.setStartTime);
			setEndTimeButton = (Button) window.findViewById(R.id.setEndTime);
			yesButton = (Button) window.findViewById(R.id._yes);

			yesButton.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					startTime.setText(queryTime_Start);
					endTime.setText(queryTime_End);
					dlg.cancel();
					DatabaseOperator databaseOperator = new DatabaseOperator();
					databaseOperator.insertQueryTime(queryTime_Start, queryTime_End);
					myHandler = new MyHanlder();
					QueryDataThreadWhenTimeChanged queryDataThreadWhenTimeChanged = new QueryDataThreadWhenTimeChanged();
					new Thread(queryDataThreadWhenTimeChanged).start();
					dialog.setTitle("检索数据");
					dialog.setMessage("数据更新中，请稍后");
					dialog.setIcon(android.R.drawable.ic_dialog_map);
					dialog.show();
				}
			});

			setEndTimeButton.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					new DatePickerDialog(MainActivity.this, setEndTime, dateAndTime.get(Calendar.YEAR), dateAndTime.get(Calendar.MONTH), dateAndTime.get(Calendar.DAY_OF_MONTH)).show();
				}
			});

			setStartTimeButton.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					new DatePickerDialog(MainActivity.this, setStartTime, dateAndTime.get(Calendar.YEAR), dateAndTime.get(Calendar.MONTH), dateAndTime.get(Calendar.DAY_OF_MONTH)).show();
				}
			});

			noButton.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dlg.cancel();
				}
			});
		}
	};

	public String modifyMonth(int value) {
		String res = "";
		if (value >= 1 && value <= 9) {
			res = "0" + value;
		} else {
			res = value + "";
		}
		return res;
	}

	public static String secondToMinutes(int second) {
		int h = 0;
		int d = 0;
		int s = 0;
		int temp = second % 3600;
		if (second > 3600) {
			h = second / 3600;
			if (temp != 0) {
				if (temp > 60) {
					d = temp / 60;
					if (temp % 60 != 0) {
						s = temp % 60;
					}
				} else {
					s = temp;
				}
			}
		} else {
			d = second / 60;
			if (second % 60 != 0) {
				s = second % 60;
			}
		}
		return h + "时" + d + "分" + s + "秒";
	}
	
	class MyGestureDetector extends SimpleOnGestureListener{

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			// TODO Auto-generated method stub
			//return super.onFling(e1, e2, velocityX, velocityY);
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
					return false;
				}
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE  && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY){
					if (currentView == maxTabIndex){
						currentView = 0;
					} else {
						currentView ++;
					}
					tabHost.setCurrentTab(currentView); 
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE  && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY){
					if (currentView == 0) {  
                        currentView = maxTabIndex;  
                    } else {  
                        currentView--;  
                    }  
                    tabHost.setCurrentTab(currentView); 
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			return false; 
		}
	}
}
